package com.superyee.commonlib.utils;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.os.SystemClock;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Display;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.superyee.commonlib.provider.UpgradeFileProvider;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AndroidUtil {

    public static void openFile(Context context, File file, String extension) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//设置intent的Action属性
        intent.setAction(Intent.ACTION_VIEW);
//获取文件file的MIME类型
        String type = getMIMEType(extension);
//设置intent的data和Type属性。
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = UpgradeFileProvider.getUriForFile(context, context.getPackageName() + ".versionProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(file);
        }
        intent.setDataAndType(uri, type);
        try {
            context.startActivity(intent); //这里最好try一下，有可能会报错。 //比如说你的MIME类型是打开邮箱，但是你手机里面没装邮箱客户端，就会报错。
        } catch (Exception e) {
            e.printStackTrace();
            AndroidUtil.showToast(context, "没有找到打开该文件的应用");
        }
    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     */
    private static String getMIMEType(String extension) {

        String type = "*/*";
        if (TextUtils.isEmpty(extension)) {
            return type;
        }
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (int i = 0; i < MIME_MapTable.length; i++) { //MIME_MapTable??在这里你一定有疑问，这个MIME_MapTable是什么？
            if (extension.equalsIgnoreCase(MIME_MapTable[i][0]))
                type = MIME_MapTable[i][1];
        }
        return type;
    }

    private static final String[][] MIME_MapTable = {
//{后缀名，MIME类型}
            {"3gp", "video/3gpp"},
            {"apk", "application/vnd.android.package-archive"},
            {"asf", "video/x-ms-asf"},
            {"avi", "video/x-msvideo"},
            {"bin", "application/octet-stream"},
            {"bmp", "image/bmp"},
            {"c", "text/plain"},
            {"class", "application/octet-stream"},
            {"conf", "text/plain"},
            {"cpp", "text/plain"},
            {"doc", "application/msword"},
            {"docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
            {"xls", "application/vnd.ms-excel"},
            {"xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
            {"exe", "application/octet-stream"},
            {"gif", "image/gif"},
            {"gtar", "application/x-gtar"},
            {"gz", "application/x-gzip"},
            {"h", "text/plain"},
            {"htm", "text/html"},
            {"html", "text/html"},
            {"jar", "application/java-archive"},
            {"java", "text/plain"},
            {"jpeg", "image/jpeg"},
            {"jpg", "image/jpeg"},
            {"webp", "image/webp"},
            {"js", "application/x-javascript"},
            {"log", "text/plain"},
            {"m3u", "audio/x-mpegurl"},
            {"m4a", "audio/mp4a-latm"},
            {"m4b", "audio/mp4a-latm"},
            {"m4p", "audio/mp4a-latm"},
            {"m4u", "video/vnd.mpegurl"},
            {"m4v", "video/x-m4v"},
            {"mov", "video/quicktime"},
            {"mp2", "audio/x-mpeg"},
            {"mp3", "audio/x-mpeg"},
            {"mp4", "video/mp4"},
            {"mpc", "application/vnd.mpohun.certificate"},
            {"mpe", "video/mpeg"},
            {"mpeg", "video/mpeg"},
            {"mpg", "video/mpeg"},
            {"mpg4", "video/mp4"},
            {"mpga", "audio/mpeg"},
            {"msg", "application/vnd.ms-outlook"},
            {"ogg", "audio/ogg"},
            {"pdf", "application/pdf"},
            {"png", "image/png"},
            {"pps", "application/vnd.ms-powerpoint"},
            {"ppt", "application/vnd.ms-powerpoint"},
            {"pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
            {"prop", "text/plain"},
            {"rc", "text/plain"},
            {"rmvb", "audio/x-pn-realaudio"},
            {"rtf", "application/rtf"},
            {"sh", "text/plain"},
            {"tar", "application/x-tar"},
            {"tgz", "application/x-compressed"},
            {"txt", "text/plain"},
            {"wav", "audio/x-wav"},
            {"wma", "audio/x-ms-wma"},
            {"wmv", "audio/x-ms-wmv"},
            {"wps", "application/vnd.ms-works"},
            {"xml", "text/plain"},
            {"z", "application/x-compress"},
            {"zip", "application/x-zip-compressed"},
            {"", "*/*"}
    };


    public static boolean isNetworkConnection(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    NetworkCapabilities capabilities = connectivity.getNetworkCapabilities(connectivity.getActiveNetwork());
                    if (capabilities != null) {
                        if (capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
                            return true;
                        }
                    }
                } else {
                    NetworkInfo info = connectivity.getActiveNetworkInfo();
                    if (info != null && info.isAvailable()) {
                        if (info.getState() == NetworkInfo.State.CONNECTED) {
                            return true;
                        }
                    }
                }
            }
        } catch (Exception e) {
            return true;
        }
        return false;
    }

    /**
     * EditText竖直方向是否可以滚动
     *
     * @param editText 需要判断的EditText
     * @return true：可以滚动   false：不可以滚动
     */
    public static boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() - editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if (scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }


    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param fontScale （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(float pxValue, float fontScale) {
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @param fontScale （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int sp2px(float spValue, float fontScale) {
        return (int) (spValue * fontScale + 0.5f);
    }

    public static void dismissLoading(Dialog loadingDialog) {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.dismiss();
        }
    }

    /**
     * 解决Android2.2版本之前的httpconnection连接的bug
     */
    public static void disableConnectionReuseIfNecessary() {
        if (hasHttpConnectionBug()) {
            System.setProperty("http.keepAlive", "false");
        }
    }

    public static boolean hasHttpConnectionBug() {
        return Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO;
    }


    /**
     * 获取进程号对应的进程名
     *
     * @param pid 进程号
     * @return 进程名
     */
    public static String getProcessName(int pid) {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/" + pid + "/cmdline"));
            String processName = reader.readLine();
            if (!TextUtils.isEmpty(processName)) {
                processName = processName.trim();
            }
            return processName;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
        return null;
    }

    /**
     * 跳转到app设置详情页
     *
     * @param context
     * @param packagename
     * @return
     */
    public static boolean goToAppDetail(Context context, String packagename) {
        try {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.fromParts("package", packagename, null));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * sdcard是否可读写
     *
     * @return
     */
    public static boolean isSdcardReady() {
        return Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
    }

    /**
     * @return
     */
    public static boolean isSdcardAvailable() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(sdcardDir.getPath());
            long availCount = sf.getAvailableBlocks();
            long blockSize = sf.getBlockSize();
            long availSize = availCount * blockSize / 1024;

            if (availSize >= 3072) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 获取sd卡剩余大小
     */
    public static long getAvailaleSize() {
        if (Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState())) {
            File sdcardDir = Environment.getExternalStorageDirectory();
            StatFs sf = new StatFs(sdcardDir.getPath());
            long availCount = sf.getAvailableBlocks();
            long blockSize = sf.getBlockSize();
            long availSize = availCount * blockSize;
            return availSize;
        }
        return 0;

    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 在某个Activity中隐藏输入法
     *
     * @param context
     */
    public static void hideIME(Activity context) {
        if (context == null) {
            return;
        }
        try {
            ((InputMethodManager) context
                    .getSystemService(Activity.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(context.getCurrentFocus()
                                    .getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        }
    }

    /**
     * 获取版本号
     */
    public static int getVerCode(Context context) {
        int verCode = -1;
        try {
            verCode = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return verCode;
    }

    /**
     * 获取版本名称
     */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return verName;
    }

    /**
     * 获取android系统版本号
     */
    public static String getAndroidVerCode(Context context) {
        String androidVerCode = "";
        try {
            androidVerCode = Build.VERSION.RELEASE;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return androidVerCode;
    }

    /**
     * 显示键盘
     *
     * @param view
     */
    public static void showKeyboard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        imm.showSoftInput(view, 0);
    }

    /**
     * 隐藏键盘
     */
    public static void hideKeyboard(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (view.getWindowToken() != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    private static long lastClickTime;
    private static int mLastClickViewId;
    private static int CLICK_REPEATTIME = 400;
    private static long mLastClickTime;

    /**
     * 判断用户连续点击按钮间隔
     *
     * @return
     */
    public static boolean isFastDoubleClick() {
        long time = SystemClock.uptimeMillis();
        if (time - lastClickTime < CLICK_REPEATTIME) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 判断同一个组件是否快速点击
     *
     * @param view
     * @return
     */
    public static boolean isFastDoubleClick(View view) {
        boolean isRepeatClick = false;

        if (view == null) {
            return false;
        }
        int tmpClickViewId = view.getId();
        long tmpClickTime = System.currentTimeMillis();

        if (tmpClickViewId == mLastClickViewId) {
            if (tmpClickTime - lastClickTime <= CLICK_REPEATTIME) {
                isRepeatClick = true;
            } else {
                mLastClickTime = tmpClickTime;
            }
        } else {
            isRepeatClick = false;
            mLastClickTime = tmpClickTime;
            mLastClickViewId = tmpClickViewId;
        }

        return isRepeatClick;
    }

    private static WeakReference<Toast> mToastReference;

    /**
     * toast显示工具
     */
    public static void showToast(Context context, String msg) {
        if (mToastReference == null || mToastReference.get() == null) {
            Toast toast = Toast.makeText(context.getApplicationContext(), msg, Toast.LENGTH_SHORT);
            mToastReference = new WeakReference<>(toast);
            toast.show();
        } else {
            mToastReference.get().cancel();
            Toast toast = Toast.makeText(context.getApplicationContext(), msg, Toast.LENGTH_SHORT);
            mToastReference = new WeakReference<>(toast);
            toast.show();
        }
    }

    public static void clearToast() {
        if (mToastReference != null && mToastReference.get() != null) {
            mToastReference.get().cancel();
        }
    }

    /**
     * 获取imsi
     */
    @SuppressLint("MissingPermission")
    public static String getImsi(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = mTelephonyMgr.getSubscriberId();
        return imsi;
    }

    /**
     * 获取imei
     */
//    public static String getImei(Context context) {
//        TelephonyManager mTelephonyMgr = (TelephonyManager) context
//                .getSystemService(Context.TELEPHONY_SERVICE);
//        String imei = mTelephonyMgr.getDeviceId();
//        return imei;
//    }
    public static String getAndroidID(Context context) {
        String m_szAndroidID = Settings.Secure.getString(context.getContentResolver(),
                Settings.Secure.ANDROID_ID);
        return m_szAndroidID;
    }

    private static final String marshmallowMacAddress = "02:00:00:00:00:00";
    private static final String fileAddressMac = "/sys/class/net/wlan0/address";

    @SuppressLint("MissingPermission")
    public static String getAdresseMAC(Context context) {
        WifiManager wifiMan = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInf = wifiMan.getConnectionInfo();

        if (wifiInf != null && marshmallowMacAddress.equals(wifiInf.getMacAddress())) {
            String result = null;
            try {
                result = getAdressMacByInterface();
                if (result != null) {
                    return result;
                } else {
                    result = getAddressMacByFile(wifiMan);
                    return result;
                }
            } catch (IOException e) {
                AppLog.printD(AndroidUtil.class.getSimpleName(), "Erreur lecture propriete Adresse MAC");
            } catch (Exception e) {
                AppLog.printD(AndroidUtil.class.getSimpleName(), "Erreur lecture propriete Adresse MAC ");
            }
        } else {
            if (wifiInf != null && wifiInf.getMacAddress() != null) {
                return wifiInf.getMacAddress();
            } else {
                return "";
            }
        }
        return marshmallowMacAddress;
    }

    private static String getAdressMacByInterface() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (nif.getName().equalsIgnoreCase("wlan0")) {
                    byte[] macBytes = nif.getHardwareAddress();
                    if (macBytes == null) {
                        return "";
                    }
                    StringBuilder res1 = new StringBuilder();
                    for (byte b : macBytes) {
                        res1.append(String.format("%02X:", b));
                    }

                    if (res1.length() > 0) {
                        res1.deleteCharAt(res1.length() - 1);
                    }
                    return res1.toString();
                }
            }

        } catch (Exception e) {
            AppLog.printD(AndroidUtil.class.getSimpleName(), "Erreur lecture propriete Adresse MAC ");
        }
        return null;
    }

    @SuppressLint("MissingPermission")
    private static String getAddressMacByFile(WifiManager wifiMan) throws Exception {
        String ret = null;
        try {
            int wifiState = wifiMan.getWifiState();
            wifiMan.setWifiEnabled(true);
            File fl = new File(fileAddressMac);
            FileInputStream fin = new FileInputStream(fl);
            ret = crunchifyGetStringFromStream(fin);
            fin.close();

            boolean enabled = WifiManager.WIFI_STATE_ENABLED == wifiState;
            wifiMan.setWifiEnabled(enabled);
        } catch (Exception e) {

        }
        return ret;
    }

    private static String crunchifyGetStringFromStream(InputStream crunchifyStream) throws IOException {
        if (crunchifyStream != null) {
            Writer crunchifyWriter = new StringWriter();

            char[] crunchifyBuffer = new char[2048];
            try {
                Reader crunchifyReader = new BufferedReader(new InputStreamReader(crunchifyStream, "UTF-8"));
                int counter;
                while ((counter = crunchifyReader.read(crunchifyBuffer)) != -1) {
                    crunchifyWriter.write(crunchifyBuffer, 0, counter);
                }
            } finally {
                crunchifyStream.close();
            }
            return crunchifyWriter.toString();
        } else {
            return "No Contents";
        }
    }


    /**
     * 判断SIM卡是否存在
     *
     * @param context
     * @return
     */
    public static boolean isSimState(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        int simState = mTelephonyMgr.getSimState();
        if (simState == TelephonyManager.SIM_STATE_ABSENT
                || simState == TelephonyManager.SIM_STATE_UNKNOWN) {
            return false;
        }
        return true;
    }


    /**
     * 判断是否为手机号，方法倒数第11位为1
     *
     * @param number 号码
     * @return
     */
    public static boolean isPhoneNumb(String number) {
        if (TextUtils.isEmpty(number) || number.length() < 11) {
            return false;
        }
        int position = number.length() - 11;
        if (number.charAt(position) == '1') {
            return true;
        }
        return false;
    }

    public static boolean isTelephoneN(String str) {
        boolean b = false;
        if (!TextUtils.isEmpty(str)) {
            str = str.replaceAll("-", "");
            str = str.replaceAll(" ", "");
            Pattern p = Pattern
                    .compile("1([\\d]{10})|((\\+[0-9]{2,4})?\\(?[0-9]+\\)?-?)?[0-9]{7,9}");
            Matcher m = p.matcher(str);
            b = m.find();
        }
        return b;
    }

    /**
     * 获取电话号码
     */
    @SuppressLint("MissingPermission")
    public static String getTel(Context context) {
        TelephonyManager mTelephonyMgr = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        String tel = mTelephonyMgr.getLine1Number();
        return tel;
    }

    public static void showDial(Context context, String mobile) {
        try {
            Intent intent = new Intent(Intent.ACTION_DIAL);
            intent.setData(Uri.parse("tel:" + mobile));
            if (intent.resolveActivity(context.getPackageManager()) != null) {
                context.startActivity(intent);
            }
        } catch (Exception e) {
            AndroidUtil.showToast(context, "唤起系统拨号盘失败!");
        }
    }

    /**
     * 拨打电话
     */
    public static void startComposeCall(String mobileNum, Context context) {
        if (TextUtils.isEmpty(mobileNum)) {
            AndroidUtil.showToast(context, "非法号码");
            return;
        }
//		if (isJI(mobileNum)&&JJHSharedPreferences.getInstence().getBoolean(StaticConstant.SETTING_VOIP, true)) {
//			String voipAccount = ComContactLogic.getInstence()
//					.getComContactByNumber(mobileNum).getVoipAccount();
//			makeVOIPCall(context, mobileNum, voipAccount);
//		} else {
        startNormalCall(mobileNum, context);
//		}

    }

    /**
     * @param mobileNum
     * @param context
     */
    @SuppressLint("MissingPermission")
    public static void startNormalCall(String mobileNum, Context context) {
        try {
            // 1.普通拨号
            Intent intent = new Intent(Intent.ACTION_CALL, Uri.fromParts("tel",
                    mobileNum, null));
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            context.startActivity(intent);
        } catch (Exception e) {
            AndroidUtil.showToast(context, "呼叫失败");
        }
    }


    /**
     * 发送短信
     *
     * @return返回是否发送成功
     */
    public static boolean sendSMS(String number, String content,
                                  PendingIntent sentIntent) {
        if (!StringUtil.isEmpty(number) && !StringUtil.isEmpty(content)) {
            SmsManager smsManager = SmsManager.getDefault();
            try {
                ArrayList<String> con = smsManager.divideMessage(content);
                for (String cont : con) {
                    smsManager.sendTextMessage(number, null, cont, sentIntent,
                            null);
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    public static void ToSendSms(Context context, String number, String content) {
        try {
            Uri smsUri = Uri.parse("smsto:" + number);
            Intent smsIntent = new Intent(Intent.ACTION_SENDTO, smsUri);
            smsIntent.putExtra("sms_body", content);
            context.startActivity(smsIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启GPU加速
     *
     * @param window
     */
    public static void openGPU(Window window) {
        try {
            // 反射出来硬件加速参数，兼容2.3版本
            Field field = WindowManager.LayoutParams.class
                    .getField("FLAG_HARDWARE_ACCELERATED");
            Field field2 = WindowManager.LayoutParams.class
                    .getField("FLAG_HARDWARE_ACCELERATED");
            if (field != null && field2 != null) {
                window.setFlags(field.getInt(null), field2.getInt(null));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断是否为json
     *
     * @param json
     * @return
     */
    public static boolean isJson(String json) {
        boolean b = false;
        if (json != null && json != "") {
            try {
                new JsonParser().parse(json);
                b = true;
            } catch (JsonParseException e) {
                b = false;
            }

        }
        return b;
    }

    public static void sendMail(Context context, String mail, String title,
                                String content) {
        try {
            // String[] email = {mail}; // 需要注意，email必须以数组形式传入
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("message/rfc822"); // 设置邮件格式
            // intent.setType("plain/text");
            intent.putExtra(Intent.EXTRA_EMAIL, mail); // 接收人
            intent.putExtra(Intent.EXTRA_SUBJECT, title); // 主题
            intent.putExtra(Intent.EXTRA_TEXT, content); // 正文
            context.startActivity(intent);
            // context.startActivity(Intent.createChooser(intent, "请选择邮件应用"));
        } catch (Exception e) {
        }
    }

    public static void sendMailTo(Context context, String mail, String title,
                                  String content) {
        try {
            Intent data = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:"
                    + mail));
            data.putExtra(Intent.EXTRA_SUBJECT, title);
            data.putExtra(Intent.EXTRA_TEXT, content);
            context.startActivity(Intent.createChooser(data, "请选择邮件应用"));
        } catch (Exception e) {
        }
    }

    public static String ToDBC(String input) {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    public static int getScreenWidth(Context context) {
        WindowManager manager = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        return display.getWidth();
    }

    // 获取屏幕的高度
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    public static int getStatusHeight(Context context) {
//		try {
//			 Class c = Class.forName("com.android.internal.R$dimen");
//			 Object obj = c.newInstance();
//			 Field field = c.getField("status_bar_height");
//			 int x = Integer.parseInt(field.get(obj).toString());
//			 int y = getResources().getDimensionPixelSize(x);
//		} catch (ClassNotFoundException e) {
//			e.printStackTrace();
//		} catch (java.lang.InstantiationException e) {
//			e.printStackTrace();
//		} catch (IllegalAccessException e) {
//			e.printStackTrace();
//		} catch (NoSuchFieldException e) {
//			e.printStackTrace();
//		}

        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    @TargetApi(14)
    public static int getNavigationBarHeight(Context context) {
        Resources res = context.getResources();
        int result = 0;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            if (hasNavBar(context)) {
                String key;
                boolean mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
                if (mInPortrait) {
                    key = "navigation_bar_height";
                } else {
                    key = "navigation_bar_height_landscape";
                }
                return getInternalDimensionSize(res, key);
            }
        }
        return result;
    }

    private static int getInternalDimensionSize(Resources res, String key) {
        int result = 0;
        int resourceId = res.getIdentifier(key, "dimen", "android");
        if (resourceId > 0) {
            result = res.getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @TargetApi(14)
    public static boolean hasNavBar(Context context) {
        Resources res = context.getResources();
        int resourceId = res.getIdentifier("config_showNavigationBar", "bool", "android");
        if (resourceId != 0) {
            boolean hasNav = res.getBoolean(resourceId);
            String sNavBarOverride = null;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                try {
                    Class c = Class.forName("android.os.SystemProperties");
                    Method m = c.getDeclaredMethod("get", String.class);
                    m.setAccessible(true);
                    sNavBarOverride = (String) m.invoke(null, "qemu.hw.mainkeys");
                } catch (Throwable e) {
                    sNavBarOverride = null;
                }
            }
            // check override flag (see static block)
            if ("1".equals(sNavBarOverride)) {
                hasNav = false;
            } else if ("0".equals(sNavBarOverride)) {
                hasNav = true;
            }
            return hasNav;
        } else { // fallback
            return !ViewConfiguration.get(context).hasPermanentMenuKey();
        }
    }

    /**
     * 是否是魅族手机
     *
     * @return
     */
    public static boolean isMeiZu() {
        if (getBrand().toLowerCase().contains("meizu")) {
            return true;
        }
        return false;
    }

    public static String getBrand() {
        return Build.BRAND == null ? "" : Build.BRAND;
    }

    public static <T> Object toObject(String s, Class<T> t) {
        if (s != null) {
            Gson gson = new Gson();
            return gson.fromJson(s, t);
        }
        return null;
    }

    public static <T> String toString(T o) {
        String s = null;
        if (o != null) {
            Gson gson = new Gson();
            s = gson.toJson(o);
        }
        return s;
    }

    /**
     * app是否切入后台
     *
     * @param context
     * @return
     */
    public static boolean isBackground(Context context) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    // 后台
                    return true;
                } else {
                    // 前台
                    return false;
                }
            }
        }
        return false;
    }


}
